package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

type Student struct {
	Id         int
	Email      string
	First_Name string
	Last_Name  string
}

func main() {
	db, e := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/demo")
	ErrorCheck(e)
	defer db.Close()

	PingDB(db)

	sql := "INSERT INTO students(email, first_name, last_name) VALUES ('admin@gmail.com', 'admin','admin')"

	resI, err := db.Exec(sql)

	if err != nil {
		panic(err.Error())
	}

	lastId, err := resI.LastInsertId()

	if err != nil {
		ErrorCheck(err)
	}

	fmt.Printf("The last inserted row id: %d\n", lastId)

	// delete data
	stmt, e := db.Prepare("delete from students where id=?")
	ErrorCheck(e)

	// delete 1st student
	resD, e := stmt.Exec("1")
	ErrorCheck(e)

	// affected rows
	a, e := resD.RowsAffected()
	ErrorCheck(e)

	fmt.Println(a) // 1

	resR, err := db.Query("SELECT * FROM students")

	defer resR.Close()

	if err != nil {
		log.Fatal(err)
	}

	for resR.Next() {

		var student Student
		err := resR.Scan(&student.Id, &student.Email, &student.First_Name, &student.Last_Name)

		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("%v\n", student)
	}

	//Update db
	stmtU, e := db.Prepare("update students set First_Name=? where id=?")
	ErrorCheck(e)

	// execute
	resU, e := stmtU.Exec("Ramesh", "1")
	ErrorCheck(e)

	u, e := resU.RowsAffected()
	ErrorCheck(e)
}

func ErrorCheck(err error) {
	if err != nil {
		panic(err.Error())
	}
}

func PingDB(db *sql.DB) {
	err := db.Ping()
	ErrorCheck(err)
}
